#include "stdafx.h"
#include "CdnProfilerFn.h"
#include "CdnProfTimer.h"

using namespace std;

namespace prof
{
	//-----------------------------------------------------
	/**
	* Ctor
	*/
	CdnProfilerFn::CdnProfilerFn(const char* name, CdnProfilerFn* pParent)
		: m_name(name),
		  m_pParent(pParent),
		  m_pTimer(new CdnProfTimer()),
		  m_childrenElapsedTime(0.0f),
		  m_myProcessingTime(0.0f)
	{

	}

	//-----------------------------------------------------
	/**
	* Dtor
	*/
	CdnProfilerFn::~CdnProfilerFn()
	{
		ChildrenList::iterator it = m_children.begin();
		for (; it != m_children.end(); ++it)
		{
			delete it->second;
		}

		m_children.clear();

		if (m_pTimer)
		{
			delete m_pTimer;
		}
	}

	//-----------------------------------------------------
	/**
	* Adds a child function to the list and returns it
	*/
	CdnProfilerFn* CdnProfilerFn::StartChildFunction(const char* name)
	{
		string sName(name);
		ChildrenList::iterator it = m_children.find(sName);
		CdnProfilerFn* fn = 0;
		if (it == m_children.end())
		{
			fn = new CdnProfilerFn(name, this);
			m_children.insert(make_pair(sName, fn));
			fn->Start();
		}
		else
		{
			fn = it->second;
			fn->Start();
		}

		return fn;
	}

	//-----------------------------------------------------
	/**
	* Gets the elapsed time for a child in the list
	*/
	void CdnProfilerFn::StopChildFunction(const char* name)
	{
		string sName(name);
		ChildrenList::iterator it = m_children.find(sName);
		if (it != m_children.end())
		{
			it->second->Stop();
		}
	}

	//-----------------------------------------------------
	/**
	* Starts the function's timer
	*/
	void CdnProfilerFn::Start()
	{
		m_pTimer->StartTimer();
	}

	//-----------------------------------------------------
	/**
	* Gets elapsed time and returns it to the parent
	*/
	void CdnProfilerFn::Stop()
	{
		float elapsedTime = m_pTimer->GetElapsedTime();

		if (m_pParent)
		{
			m_pParent->m_childrenElapsedTime += elapsedTime;
		}
		
		m_myProcessingTime += elapsedTime;
	}
}
